<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SocketIO Chat</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="../static/assets/css/Chat.css" rel="stylesheet">
    <!-- icons -->
    <link href="../static/assets/img/tubiao.png" rel="icon">
</head>
<body>
    <div id="chat-container">
        <div id="chat-box"></div>
        <form id="message-form">
            <input type="text" id="message-input" placeholder="请输入内容" maxlength="50" required>
            <button type="submit">发送</button>
        </form>
        <!-- 离开按钮 -->
        <button id="leave-button" href="/">离开</button>
    </div>


    <script>
        var socket = io();
        // Joining the chat room
        var username = '{{ username }}';
        var friend = '{{ friend_name }}';
        var room = username + '->' + friend; //set the room here
        var receive = friend + '->' + username;
        socket.emit('join', {'username': username, 'room': room, 'receive':receive});

        // Event listener for receiving messages
        socket.on('message', function(msg) {
            $('#chat-box').append('<p>' + msg.msg + '</p>');
        });

        // Event listener for sending messages
        $('#message-form').submit(function(e) {
            e.preventDefault();
            var message = $('#message-input').val();
            socket.emit('text', {'username': username,'friend': friend, 'msg': message, 'room': room, 'receive':receive});
            $('#message-input').val('');
        });

        // Event listener for leaving the chat room
        window.addEventListener("unload", function(event) {
            socket.emit('left', {'username': username, 'room': room, 'receive':receive});
        });

        // 离开按钮点击事件监听器
        $('#leave-button').click(function() {
            socket.emit('left', {'username': username, 'room': room, 'receive': receive});
             history.back(); // 点击按钮后退回上一个页面
        });
    </script>
</body>
</html>
